package com.tm;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.tm.controller.InstrumentController;
import com.tm.pojo.Instrument;

@SuppressWarnings("serial")
public class Populate extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);	
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			UserService userService = UserServiceFactory.getUserService();
			if (userService.isUserLoggedIn() && userService.getCurrentUser().getNickname().equals("vahe@andonians.com")) {
				
				InstumentsTextFileLoader loader = new InstumentsTextFileLoader("PopulateData.txt");
				Iterator<Instrument> i = loader.iterator();
				while (i.hasNext()) {
					Instrument instrument = i.next();
					if (instrument != null) {
						InstrumentController.getInstance().saveNewInstrument(instrument);
					}
				}
			}
		} catch (Throwable e) {
			PrintWriter out = resp.getWriter();
			out.println("Error: " + e.getMessage());
		}
	}
}
